
<!DOCTYPE html>
<html lang="zh-CN" class="relative min-full">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <meta name="csrf-token" content="jgFYChJ8Kf8x9F3iRbNJ5SONxV27KVP6LfwjlYNP">
        <meta name="keywords" content="Lsky Pro,lsky,兰空图床"/>
        <meta name="description" content="Lsky Pro, Your photo album on the cloud."/>

        <title>学时证上传</title>

        <!-- Fonts -->
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">
        <link rel="stylesheet" href="./css/fontawesome.css">
        <link rel="stylesheet" href="./css/markdown-css/github-markdown-light.css">
        <!-- Styles -->
        <link rel="stylesheet" href="./css/common.css?t=20220817">
        <link rel="stylesheet" href="./css/app.css?t=20220817">
        <link href="//mirror.fe80.cn/bootstrap/4.6.0/css/bootstrap.min.css" rel="stylesheet">
        <style>
/* 滚动条样式 */
::-webkit-scrollbar {
    /*滚动条整体样式*/
    width : 5px;  /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
}
::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 3px;
    box-shadow   : inset 0 0 3px rgba(0, 0, 0, 0.2);
    background   : #007bff;
}
::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow   : inset 0 0 3px rgba(0, 0, 0, 0.2);
    border-radius: 3px;
    background   : #ededed;
}
        </style>
    </head>
    <body class="font-sans antialiased">
        <div class="min-h-screen text-gray-900 bg-gray-100">
            <div class="py-14">
                <header class="w-full h-14 bg-gray-700 text-white flex justify-center fixed top-0 z-[9]">
                    <div class="container mx-auto px-5 sm:px-10 md:px-10 lg:px-10 xl:px-10 2xl:px-60 flex justify-between items-center">
                        <div class="flex justify-start items-center max-w-[70%]">
                            <a href="." class="text-white text-xl truncate">学时证上传</a>
                        </div>
                        <div class="flex justify-end items-center space-x-4">
                <!-- Strategies dropdown -->
                <div class="relative" x-data="{ open: false }" @click.outside="open = false" @close.stop="open = false" x-cloak>
                    <div @click="open = ! open">
                        <button type="button" class="bg-gray-800 flex items-center text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" id="user-menu-button" aria-expanded="false" aria-haspopup="true">
                            <span class="sr-only">Open strategies menu</span>
                            <div class="h-8 w-8 rounded-full flex items-center justify-center bg-white">
                                <i class="fas fa-server text-gray-900"></i>
                            </div>
                            <span class="px-2 sm:block hidden" id="strategy-selected" data-id="0">获取中...</span>
                        </button>
                    </div>

                    <div x-show="open"
                        x-transition:enter="transition ease-out duration-200"
                        x-transition:enter-start="transform opacity-0 translate-y-9"
                        x-transition:enter-end="transform opacity-100 translate-y-0"
                        x-transition:leave="transition ease-in duration-75"
                        x-transition:leave-start="transform opacity-100 translate-y-0"
                        x-transition:leave-end="transform opacity-0 translate-y-9"
                        class="absolute z-[9] origin-top-right right-0 mt-2 w-48 rounded-md shadow-[10px_0px_50px_-15px_rgba(0,0,0,0.25)] py-1 bg-white "
                        role="menu"
                        aria-orientation="vertical"
                        aria-labelledby="user-menu-button"
                        tabindex="-1"
                        style="display: none"
                    >
                        <div id="strategies">
                        <a class="block px-4 py-2 active:bg-gray-100 text-sm text-gray-700 truncate hover:bg-sky-500 hover:text-white" role="menuitem" tabindex="-1" data-id="1" href="javascript:void(0)" @click="open = false">默认本地策略</a>
                        </div>
                    </div>
                </div>


                <!-- Profile dropdown -->
                <div class="relative" x-data="{ open: false }" @click.outside="open = false" @close.stop="open = false" x-cloak>
                    <div @click="open = ! open">
                        <button type="button" class="bg-gray-800 flex items-center text-sm rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" id="user-menu-button" aria-expanded="false" aria-haspopup="true">
                            <span class="sr-only">Open user menu</span>
                            <img class="h-8 w-8 rounded-full" src="http://comeround.cn/public/images/cat.jpg" alt="">
                            <span class="px-2 sm:block hidden">超级管理员</span>
                        </button>
                    </div>

                    <div x-show="open"
                        x-transition:enter="transition ease-out duration-200"
                        x-transition:enter-start="transform opacity-0 translate-y-9"
                        x-transition:enter-end="transform opacity-100 translate-y-0"
                        x-transition:leave="transition ease-in duration-75"
                        x-transition:leave-start="transform opacity-100 translate-y-0"
                        x-transition:leave-end="transform opacity-0 translate-y-9"
                        class="absolute z-[9] origin-top-right right-0 mt-2 w-48 rounded-md shadow-[10px_0px_50px_-15px_rgba(0,0,0,0.25)] py-1 bg-white "
                        role="menu"
                        aria-orientation="vertical"
                        aria-labelledby="user-menu-button"
                        tabindex="-1"
                        style="display: none">
                        <!-- Authentication -->
                        <form method="POST" action="./logout">
                            <input type="hidden" name="_token" value="jgFYChJ8Kf8x9F3iRbNJ5SONxV27KVP6LfwjlYNP">            <a class="block px-4 py-2 active:bg-gray-100 text-sm text-gray-700 truncate hover:bg-sky-500 hover:text-white" role="menuitem" tabindex="-1" href="./images">我的图片</a>
                            <a class="block px-4 py-2 active:bg-gray-100 text-sm text-gray-700 truncate hover:bg-sky-500 hover:text-white" role="menuitem" tabindex="-1" href="./dashboard">仪表盘</a>
                            <a class="block px-4 py-2 active:bg-gray-100 text-sm text-gray-700 truncate hover:bg-sky-500 hover:text-white" role="menuitem" tabindex="-1" href="./settings">设置</a>
                            <a class="block px-4 py-2 active:bg-gray-100 text-sm text-gray-700 truncate hover:bg-sky-500 hover:text-white" role="menuitem" tabindex="-1" href="./logout" onclick="event.preventDefault(); this.closest('form').submit();">注销</a>
                        </form>
                    </div>
                </div>
                </div>
                </div>
                </header>
                <div class="mt-10 container mx-auto px-5 sm:px-10 md:px-10 lg:px-10 xl:px-10 2xl:px-60">
                    <div class="pb-6 h-full">
                    <input type="file" id="picker" name="file" class="hidden" accept=".jpeg,.jpg,.png,.gif,.tif,.bmp,.ico,.psd,.webp,.pdf" multiple>

                    <div class="mb-4 p-4 bg-white rounded-md shadow-custom">
                        <h1 class="tracking-wider text-2xl text-gray-700 mb-2" style="text-shadow: -4px 4px 0 rgb(0 0 0 / 10%);">文件上传</h1>
                        <p class="text-gray-500 text-sm">
                            最大可上传 5.00 MB 的图片，上传队列最多
                            3
                            张。本站已托管 19 张图片。
                        </p>
                        <div class="mt-3 rounded-md border-2 border-dotted border-stone-300 w-full h-full" id="picker-dnd" onclick="$('#picker').click()">
                            <div id="upload-container" class="relative group flex flex-col justify-center items-center p-2 w-full h-full min-h-[150px] sm:min-h-[340px] space-y-4 text-gray-500 cursor-pointer">
                                <i id="clear" class="fas fa-times absolute top-1 right-1 w-8 h-8 flex justify-center items-center cursor-pointer text-xl text-center hidden group-hover:block text-gray-400 hover:text-gray-500"></i>
                                <p id="upload-all" title="点我上传全部"><i class="fas fa-cloud-upload-alt text-6xl hover:text-indigo-400"></i></p>
                                <p class="text-md text-center">拖拽文件到这里，支持多文件同时上传<br/>点击上面的图标上传全部已选择文件</p>
                            </div>
                            <div id="upload-preview" class="flex m-2 hidden"></div>
                        </div>
                    </div>

                    <div id="links-container" class="hidden mb-4 p-4 bg-white rounded-md relative group shadow-custom">
                        <div class="absolute top-2 right-2 flex">
                            <span id="copy-all" class="px-2 py-1 rounded-md text-xs text-gray-800 bg-gray-100 cursor-pointer hidden group-hover:block">复制全部</span>
                            <span id="clear-all" class="ml-1 px-2 py-1 rounded-md text-xs text-gray-800 bg-gray-100 cursor-pointer hidden group-hover:block">清除</span>
                        </div>
                        <div id="link-tabs" class="flex flex-nowrap overflow-scroll scrollbar-none text-sm">
                            <a href="javascript:void(0)" data-tab-name="url" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-indigo-500 active">URL</a>
                            <a href="javascript:void(0)" data-tab-name="html" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-transparent">HTML</a>
                            <a href="javascript:void(0)" data-tab-name="bbcode" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-transparent">BBCode</a>
                            <a href="javascript:void(0)" data-tab-name="markdown" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-transparent">Markdown</a>
                            <a href="javascript:void(0)" data-tab-name="markdown_with_link" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-transparent whitespace-nowrap">Markdown with link</a>
                            <a href="javascript:void(0)" data-tab-name="thumbnail_url" class="hover:bg-gray-100 flex justify-center items-center px-8 py-2 border-b-2 border-transparent whitespace-nowrap">Thumbnail url</a>
                        </div>
                        <div id="links" class="mt-2">
                            <div data-tab="url" class="space-y-2"></div>
                            <div data-tab="html" class="hidden space-y-2"></div>
                            <div data-tab="bbcode" class="hidden space-y-2"></div>
                            <div data-tab="markdown" class="hidden space-y-2"></div>
                            <div data-tab="markdown_with_link" class="hidden space-y-2"></div>
                            <div data-tab="thumbnail_url" class="hidden space-y-2"></div>
                        </div>
                    </div>

                    <div class="mb-4 p-4 bg-white rounded-md shadow-custom">
                        <table class="table">
                          <thead>
                            <tr><th>教师姓名</th><th>文件名称</th><th>文件大小</th><th>上传时间</th></tr>
                          </thead>
                          <tbody>
                            <!-- <tr><td>张三</td><td>文件地址.pdf</td><td>1830.02KB</td><td>2024-10-14 12:00:00</td></tr> -->
                          </tbody>
                        </table>
                    </div>
                </div>

                <div id="preview-modal" class="fixed z-10 inset-0 overflow-y-auto" role="dialog" aria-modal="true" x-data x-cloak x-show="$store.modal.isOpen('preview-modal')">
                    <div class="flex min-h-screen text-center md:block md:px-2 lg:px-4" style="font-size: 0">
                        <div x-transition:enter="transition ease-out duration-300"
                            x-transition:enter-start="transform opacity-0"
                            x-transition:enter-end="transform opacity-100"
                            x-transition:leave="transition ease-in duration-200"
                            x-transition:leave-start="transform opacity-100"
                            x-transition:leave-end="transform opacity-0"
                            x-show="$store.modal.isOpen('preview-modal')"
                            @click="$store.modal.close('preview-modal')"
                            class="hidden fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity md:block"
                            aria-hidden="true"
                        >
                        </div>
                        <span class="hidden md:inline-block md:align-middle md:h-screen" aria-hidden="true">&#8203;</span>

                        <div x-transition:enter="transition ease-out duration-300"
                            x-transition:enter-start="transform opacity-0 translate-y-4 md:translate-y-0 md:scale-95"
                            x-transition:enter-end="transform opacity-100 translate-y-0 md:scale-100"
                            x-transition:leave="transition ease-in duration-200"
                            x-transition:leave-start="transform opacity-100 translate-y-0 md:scale-100"
                            x-transition:leave-end="transform opacity-0 translate-y-4 md:translate-y-0 md:scale-95"
                            x-show="$store.modal.isOpen('preview-modal')"
                            class="flex text-base text-left transform transition w-full md:inline-block md:max-w-2xl md:px-4 md:my-8 md:align-middle lg:max-w-4xl"
                        >
                        <div class="w-full relative flex bg-white px-4 pt-14 pb-8 overflow-hidden shadow-lg sm:px-6 sm:pt-8 md:p-6 lg:p-8 md:rounded-sm">
                            <button type="button" class="absolute top-2 right-2 text-gray-400 hover:text-gray-500 sm:top-4 sm:right-4 md:top-3 md:right-3 lg:top-4 lg:right-4" @click="$store.modal.close('preview-modal')">
                                <span class="sr-only">Close</span>
                                <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>

                            <div class="flex items-center justify-center h-24 w-full" x-show="$store.modal.isLoading('preview-modal')">
                                <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-red-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                </div>

                <div class="w-full" x-show="! $store.modal.isLoading('preview-modal')">
                    <div class="rounded-lg overflow-hidden">
                        <img class="w-full h-full object-cover" src="">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="image-preview-tpl">
    <div data-id="__id__" class="w-full flex items-center p-2 mb-2 rounded-md relative bg-gray-50 overflow-hidden">
        <div class="absolute inset-0">
            <div class="w-[0%] h-full bg-gray-200 opacity-70 upload-progress"></div>
        </div>
        <div class="relative flex w-full">
            <div class="w-10 h-10 bg-gray-200 rounded-lg cursor-pointer overflow-hidden">
                <img class="w-full h-full object-cover" data-operate="preview" src="__src__">
            </div>
            <div class="flex justify-end flex-col ml-2 w-[80%] opacity-70">
                <p class="text-sm truncate">__name__</p>
                <p class="text-xs truncate">
                    <span>__info__</span>, <span class="upload-info">等待上传</span>
                </p>
            </div>
        </div>
        <div class="absolute right-2 flex space-x-2">
            <a href="javascript:void(0)" data-operate="remove" class="flex justify-center items-center block shadow-sm w-10 h-10 rounded-full text-gray-600 bg-gray-100 hover:bg-gray-200 aspect-w-1 aspect-h-1"><i class="fas fa-times"></i></a>
            <a href="javascript:void(0)" data-operate="upload" class="flex justify-center items-center block shadow-sm w-10 h-10 rounded-full text-gray-600 bg-gray-100 hover:bg-gray-200 aspect-w-1 aspect-h-1"><i class="fas fa-upload"></i></a>
        </div>
    </div>
</script>
        </div>
        <footer class="absolute bottom-0 left-0 right-0 w-full bg-gray-200">
            <p class="container mx-auto py-2 px-5 sm:px-10 md:px-10 lg:px-10 xl:px-10 2xl:px-60 text-gray-500 text-sm">
                Copyright © 2018 - present Lsky Pro. All rights reserved. &nbsp;<a href="https://beian.miit.gov.cn/" target="_blank" rel="noreferrer"></a>&nbsp;请勿上传违反中国大陆和香港法律的图片，违者后果自负。
            </p>
        </footer>
    </div>
        </div>
    </body>
    <!-- Scripts -->
    <script src="./js/app.js?t=20220817"></script>
            <script>
        let defaultStrategy = 0 || (localStorage.getItem('strategy') || 0);
        let setStrategy = function (id) {
            let isSelected = false;
            $('#strategies a').each(function () {
                if (parseInt($(this).data('id')) === parseInt(id)) {
                    localStorage.setItem('strategy', id)
                    $('#strategy-selected').text($(this).text()).data('id', id);
                    isSelected = true;

                                            if (defaultStrategy != id) {
                            axios.put('./settings/set-strategy', {id: id}).then(response => {
                                if (! response.data.status) {
                                    toastr.error(response.data.message);
                                }
                            });
                        }
                                    }
            });
            if (! isSelected) {
                let $first = $('#strategies a:first-child');
                localStorage.setItem('strategy', $first.data('id'))
                $('#strategy-selected').text($first.text()).data('id', $first.data('id'));
            }
        };

        setStrategy(defaultStrategy);

        $('#strategies a').click(function () {
            setStrategy($(this).data('id'))
        });
    </script>
    <script src="./js/blueimp-file-upload/jquery.ui.widget.js"></script>
    <script src="./js/blueimp-file-upload/jquery.iframe-transport.js"></script>
    <script src="./js/blueimp-file-upload/jquery.fileupload.js"></script>
    <script src="./js/blueimp-load-image/load-image.all.min.js"></script>
    <script src="./js/clipboard/clipboard.min.js"></script>
    <link href="//mirror.fe80.cn/limonte-sweetalert2/8.11.8/sweetalert2.min.css" rel="stylesheet">
    <script src="//mirror.fe80.cn/limonte-sweetalert2/8.11.8/sweetalert2.min.js"></script>
    <script>
let allowSuffixes = ["jpeg","jpg","png","gif","tif","bmp","ico","psd","webp","pdf"];
let maxSize = 50 * 1024 *1024; //B
let pastedAction = '1';

// +--------------------------------------
// |  阿里云代码部分
// +--------------------------------------

accessid = '';
accesskey = '';
host = 'http://dzsite.oss-cn-chengdu.aliyuncs.com';
policyBase64 = '';
signature = '';
callbackbody = '';
filename = '';
key = '';
ip = '';
expire = 0;
g_object_name = '';
g_object_name_type = 'local_name';
now = timestamp = Date.parse(new Date()) / 1000;

// 说明：获取应用服务器的签名信息
function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        // serverUrl是 用户获取 '签名和Policy' 等信息的应用服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        // serverUrl = 'http://88.88.88.88:8888/aliyun-oss-appserver-php/php/get.php'
        serverUrl = 'http://i.fe80.cn/portal/sts';
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};

// 获取文件对象的集合
function check_object_radio() {
    var tt = document.getElementsByName('myradio');
    for (var i = 0; i < tt.length ; i++ )
    {
        if(tt[i].checked)
        {
            g_object_name_type = tt[i].value;
            break;
        }
    }
}
// 检测签名是否过期，如果过期则需要重新获取
function get_signature()
{
    // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        host = obj['host'];
        policyBase64 = obj['policy'];
        accessid = obj['accessid'];
        signature = obj['signature'];
        expire = parseInt(obj['expire']);
        callbackbody = obj['callback'];
        key = obj['dir'];
        ip = obj['ip'];
        return true;
    }
    return false;
};
// 获取随机字符串，用于生成文件名
function random_string(len) {
    len = len || 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
    var maxPos = chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
// 获取文件后缀
function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}
// 生成文件名
function calculate_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name')
    {
        suffix = get_suffix(filename)
        g_object_name = key + random_string(10) + suffix
    }
    return ''
}
// 获取上传后的文件路径
function get_uploaded_object_name(filename)
{
    if (g_object_name_type == 'local_name')
    {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if(g_object_name_type == 'random_name')
    {
        return g_object_name
    }
}
// 设置上传的头部参数
function set_upload_param_001(filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;

    suffix = get_suffix(filename);
    calculate_object_name(filename);
    
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
        'ip': ip,
        'x:ip': ip,
    };
    return new_multipart_params;

    // up.setOption({
    //     'url': host,
    //     'multipart_params': new_multipart_params
    // });

    // up.start();
}

// 结束

(new ClipboardJS('#copy-all', {
    text: function(trigger) {
        let text = '';
        $('[data-tab="' + $('#link-tabs a.active').data('tab-name') + '"] p').each(function (i) {
            if (i !== 0) {
                text += '\r\n';
            }
            text += $(this).text();
        });
        return text;
    }
})).on('success', function(e) {
    if (! $(e.trigger).attr('disabled')) {
        let text = $(e.trigger).text();
        $(e.trigger).attr('disabled', true).text('复制成功');
        setTimeout(function () {
            $(e.trigger).attr('disabled', false).text(text);
        }, 1000);
    }
}).on('error', function(e) {
    toastr.warning('复制失败')
});

// 检查文件名是否符合要求
function checkName(filename){
    let previewIdname = filename.split('-');
    if(previewIdname.length >= 2){
        if(previewIdname[0].length < 2 || previewIdname[0].length > 4){
            // app.msg(false, '文件名的姓名“'+previewIdname[0]+'”不符合规范');
            Swal.fire({
                position: 'center', //定位 左上角
                type: 'error',
                title: '文件名的姓名“'+previewIdname[0]+'”不符合规范',
                showConfirmButton: false,
                timer: 1500
            });
            return false;
        }
        }else{
        Swal.fire({
            position: 'center', //定位 左上角
            type: 'error',
            title: '文件名“'+filename+'”不符合规范',
            showConfirmButton: false,
            timer: 1500
        });
        // app.msg(false, '文件名“'+filename+'”不符合规范');
        return false;
    }
    return true;
}
const UPLOAD_WAITING = 0; // 等待上传
const UPLOAD_SUCCESS = 1; // 上传成功
const UPLOAD_ERROR = 2; // 上传失败
let $previews = $('#upload-preview');
let $links = $('#links-container');
let $picker = $('#picker');
let queue = []; // 文件队列
let excludes = ['psd', 'tif']; // 排除支持预览的格式
/**
 * 设置状态
 * @param data
 * @param status
 * @param message
 */
const setStatus = (data, status, message) => {
    queue[data.guid].status = data.status = status;
    let $info = data.$preview.find('.upload-info');
    $info.removeClass('text-green-500 text-red-500')
    let msg = '';
    switch (status) {
        case UPLOAD_WAITING:
            msg = '等待上传';
            break;
        case UPLOAD_SUCCESS:
            msg = '上传成功';
            $info.addClass('text-green-800');
            break;
        case UPLOAD_ERROR:
            msg = '上传失败';
            $info.addClass('text-red-500')
            break;
    }
    $info.text(message ? message : msg);
}
$picker.fileupload({
    url: 'http://dzsite.oss-cn-chengdu.aliyuncs.com',
    autoUpload: false,
    dataType: 'json',
    headers: {
        // 'H-X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    limitMultiFileUploads: 1,
    limitConcurrentUploads: 3,
    pasteZone: $(document),
    dropZone: $('#picker-dnd'),
    formData: (form) => {
        let keylist = set_upload_param_001('', '');
        let keys = [];
        $.each(keylist, function (index, key1) {
            keys.push({name: index, value: key1});
        });
        return keys;
    },
    paste: (e, data) => {
        let files = [];
        $.each(data.files, function (index, file) {
            let name = new Date().getTime().toString();
            files[index] = new File([file], name + "." + file.name.substr(file.name.lastIndexOf('.') + 1), {
                type: file.type,
                lastModified: file.lastModified,
            });
        });
        data.files = files;
        data.from = 'paste';
    },
    add: (e, data) => { // Return true to continue adding, otherwise terminate
        let file = data.files[0];
        console.log("文件名："+file.name);
        let ch = checkName(file.name);
        if (ch === false) {
            return false;
        }
        let ext = file.name.substr(file.name.lastIndexOf('.') + 1);
        if (allowSuffixes.indexOf(ext.toLowerCase()) === -1) {
            toastr.warning(`不支持的图片格式 ${file.name}`);
            return true;
        }
        if (file.size > maxSize) {
            toastr.warning(`图片 ${file.name} 超出大小限制`);
            return true;
        }
        let guid = utils.guid();
        data.guid = guid;

        // 推送到队列
        let push = function (blob) {
            let html = $('#image-preview-tpl')
                .html()
                .replace(/__id__/g, guid)
                .replace(/__src__/g, blob)
                .replace(/__name__/g, file.name.replace(/\$/g, '$$$$'))
                .replace(/__info__/g, utils.formatSize(file.size));
            data.$preview = $previews.append(html).show().find(`[data-id="${guid}"]`);
            queue[guid] = data;
            setStatus(data, UPLOAD_WAITING);

            // 如果来源是否为粘贴，判断是否需要直接上传
            if (data.from === 'paste' && pastedAction === '2') {
                queue[guid].submit();
            }
        };

        if (excludes.indexOf(file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase()) !== -1) {
            push('');
        } else {
            loadImage(file, function (img) {
                    if (img.type === 'error') {
                        toastr.error(`文件 ${file.name} 缩略图生成失败`);
                        console.error('Error loading image file')
                    }
                    push(img.toDataURL())
                }, {
                    maxWidth: 200,
                    maxHeight: 200,
                    meta: true,
                    orientation: true,
                    canvas: true
                },
            )
        }
    },
    send: (e, data) => {
        data.$preview.find('[data-operate="upload"]').hide();
    },
    progress: (e, data) => {
        let progress = parseInt(data.loaded / data.total * 100, 10);
        let $uploadInfo = data.$preview.find('.upload-info');
        let $uploadProgress = data.$preview.find('.upload-progress');
        let rate = progress + '%';
        $uploadInfo.text('上传中...' + rate);
        $uploadProgress.css('width', rate);
    },
    done: (e, data) => {
        let response = data.result;
        if (response.status || response.Status == 'Ok') {
            // 如果开启了自动清除缩略图功能
            if (0) {
                delete queue[data.$preview.data('id')];
                data.$preview.remove();
            } else {
                setStatus(data, UPLOAD_SUCCESS)
                data.$preview.attr('uploaded', true);
            }

            // 追加链接
            let links = response.body.filename;
            for (let key in links) {
                $('#links [data-tab="' + key + '"]').append('<p class="whitespace-nowrap select-all mt-1 bg-gray-50 hover:bg-gray-200 text-gray-600 rounded px-2 py-1 cursor-pointer overflow-scroll scrollbar-none">' + links[key].toString() + '</p>')
            }

            // 添加新数据到表格中 添加到表格中的第一行
            $("tbody").prepend('<tr style="color:red;font-weight:bold;"><td>'+response.info.name+'</td><td>'+response.info.file+'</td><td>'+(response.body.size/1024).toFixed(2)+'KB</td><td>'+response.info.create_time+'</td></tr>');

            //$links.show(); //隐藏markdown部分
            utils.setCapacityProgress(response.body.size);
        } else {
            setStatus(data, UPLOAD_ERROR, "上传失败, " + response.Status);
            // 重新显示上传按钮
            data.$preview.find('[data-operate="upload"]').show();
        }
    },
    fail: (e, data) => {
        if (data.errorThrown !== 'abort') {
            // 重新显示上传按钮
            data.$preview.find('[data-operate="upload"]').show();
            if (data.jqXHR.status === 419) {
                return setStatus(data, UPLOAD_ERROR, '令牌错误，请刷新网页重试');
            }
            return setStatus(data, UPLOAD_ERROR, '服务端异常，请稍后重试');
        }
    },
    // 等同于jq的complete
    always: (e, data) => {

    }
});

$(document).on('drop dragover', (e) => e.preventDefault());
$previews.click((e) => e.stopPropagation());

$('#upload-all').click((e) => {
    // 队列中没有文件，选择则继续冒泡，选择文件
    if (Object.values(queue).filter((item) => item.status !== UPLOAD_SUCCESS).length) {
        e.stopPropagation();
        for (const key in queue) {
            if (queue[key].status !== UPLOAD_SUCCESS) {
                queue[key].submit();
            }
        }
    }
});

$previews.on('click', '[data-operate]', function (e) {
    e.stopPropagation();
    let $preview = $(this).closest('[data-id]');
    let method = $(this).data('operate');
    let id = $preview.data('id');
    if (method === 'remove') {
        queue[id].abort();
        delete queue[id];
        $preview.remove();
    }
    if (method === 'upload' && queue[id].status !== UPLOAD_SUCCESS) {
        queue[id].submit();
    }
    if (method === 'preview') {
        let file = queue[id].files[0];
        if (excludes.indexOf(file.name.substring(file.name.lastIndexOf(".") + 1).toLowerCase()) === -1) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function (e) {
                $('#preview-modal img').attr('src', e.target.result);
                Alpine.store('modal').open('preview-modal')
            }
        }
    }
});

$('#clear').click(function (e) {
    e.stopPropagation();
    queue = [];
    $previews.html('');
});

$('[data-tab-name]').click(function () {
    $(this).removeClass('active border-transparent')
        .addClass('active border-indigo-500')
        .siblings()
        .removeClass('active border-indigo-500')
        .addClass('border-transparent');
    $('[data-tab]').hide();
    $('[data-tab="' + $(this).data('tab-name') + '"]').show()
});

$('#clear-all').click(function () {
    $('[data-tab]').html('')
    $links.hide();
});
// 预加载所有上传记录
$.post('http://i.fe80.cn/shubao/book/list',{},function(res){
    if(res.list){
      $.each(res.list,function(index,item){
          // 添加到表格中的第一行
          $("tbody").append('<tr><td>'+item.name+'</td><td>'+item.file+'</td><td>'+(item.size/1024).toFixed(2)+'KB</td><td>'+item.create_time+'</td></tr>');
      });
    }
});
    </script>
</html>
